import { ref, watch } from "vue";
import { useDebounceFn } from "@vueuse/core";
import { searchContracts } from "@/api/refdata";
import type { ContractData } from "@/types/contract.types";
import { useRenderIcon } from "../ReIcon/src/hooks";

export const DEFAULT_SEARCH_LIMIT = 20;

export const MDominantIcon = useRenderIcon("mdi:alphabet-m-box", {
  width: 16,
  height: 16,
  color: "var(--el-color-danger)"
});

export function useSymbolSearch(options?: {
  initialQuery?: string;
  debounceMs?: number;
  limit?: number;
}) {
  const query = ref("");
  const loading = ref(false);
  const results = ref<ContractData[]>([]);

  const effectiveLimit = options?.limit ?? DEFAULT_SEARCH_LIMIT;
  const debounceMs = options?.debounceMs ?? 250;

  async function doSearch(search: string, limit: number = effectiveLimit) {
    const normalized = (search ?? "").trim();
    if (!normalized) {
      results.value = [];
      return;
    }
    loading.value = true;
    try {
      const resp = await searchContracts({ search: normalized, limit });
      results.value = resp?.data ?? [];
    } catch (e) {
      console.error(e);
      results.value = [];
    } finally {
      loading.value = false;
    }
  }

  const debouncedDoSearch = useDebounceFn((val: string) => {
    void doSearch(val, effectiveLimit);
  }, debounceMs);

  watch(query, newVal => {
    debouncedDoSearch(newVal);
  });

  if (options?.initialQuery && options.initialQuery.trim().length > 0) {
    query.value = options.initialQuery;
  }

  return { query, loading, results, doSearch };
}

export async function resolveContractBySymbol(
  symbol: string
): Promise<ContractData | null> {
  if (!symbol || symbol.trim().length === 0) return null;
  try {
    const resp = await searchContracts({
      search: symbol,
      limit: DEFAULT_SEARCH_LIMIT
    });
    const list = resp?.data ?? [];
    const exact = list.find(item => item.symbol === symbol);
    return exact ?? null;
  } catch (e) {
    console.error(e);
    return null;
  }
}
